package com.example.boot.security;

import com.example.boot.security.sms.SmsCodeAuthenticationProvider;
import com.example.interceptor.JwtAuthenticationTokenFilter;
import com.example.service.Impl.SpringSecurityDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * 权限认证配置类
 *
 * @author ding
 * @since 2024/7/23
 */
@Configuration
@EnableWebSecurity
//开启注解权限认证功能    jsr250Enabled = true   securedEnabled = true
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    //放行资源  通过split进行分割
    public static final String STATIC_PATH = "";

    //账号密码登录认证过滤器
    @Autowired
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    @Autowired
    private SpringSecurityDetailsService securityDetailsService;

    // 认证失败处理器
    @Autowired
    private AuthenticationEntryPoint authenticationEntryPoint;

    //授权失败处理器
    @Autowired
    private AccessDeniedHandler accessDeniedHandler;

    //密码处理器
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }


    /**
     * 认证配置
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            //关闭CSRF（跨服务器的请求访问）,默认是开启的，设置为禁用；如果使用自定义登录页面需要关闭此项，否则登录操作会被禁用403
                .csrf().disable()
                // 禁用session (前后端分离项目，不通过Session获取SecurityContext)
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                //请求认证配置
                .authorizeRequests()
                .antMatchers("/login", "/findUserName", "/socket/**",
                        "/getPermCode", "/swagger-ui.html",  "/webjars/**", "/swagger-resources/**", "/v2/**",
                        "/swagger-ui.html", "/doc.html", "/files/**",
                        "/register", "/sendSms/**", "/validSms").permitAll()
                .anyRequest().authenticated();

        //添加token过滤器
//        http.addFilterBefore( smsCodeCheckFilter, UsernamePasswordAuthenticationFilter.class);
        http.addFilterBefore( jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);

        // 配置异常处理器
        http.exceptionHandling()
                //认证失败
                .authenticationEntryPoint(authenticationEntryPoint)
                //授权失败
                .accessDeniedHandler(accessDeniedHandler);

        // 退出登录处理器 清除redis 中token GET请求
//        http.logout().logoutUrl("/admin/logout");

        //Spring Security 允许跨域
        http.cors();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 加入自定义的安全认证  如果自定义了多套身份验证系统  需要在这添加重写的 AuthenticationProvider
        auth.userDetailsService(this.securityDetailsService)
                .passwordEncoder(this.passwordEncoder())
                .and()
                //添加自定义的认证管理类
                .authenticationProvider(smsAuthenticationProvider())
                .authenticationProvider(authenticationProvider());
    }

    //注入AuthenticationManager 进行用户认证
    @Bean
    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    //账号密码
    @Bean
    public AuthenticationProvider authenticationProvider(){
        AuthenticationProvider authenticationProvider =  new UsernameAuthenticationProvider();
        return authenticationProvider;
    }

    //手机验证码
    @Bean
    public AuthenticationProvider smsAuthenticationProvider(){
        AuthenticationProvider authenticationProvider =  new SmsCodeAuthenticationProvider();
        return authenticationProvider;
    }
}
